<template>
  <div class="upload-container">
    <!-- 文件夹选择 -->
    <el-card class="folder-card">
      <template #header>
        <div class="card-header">
          <span>选择文件夹</span>
          <el-button type="primary" size="small" @click="$router.push('/new')">
            新建文件夹
          </el-button>
        </div>
      </template>
      
      <el-select v-model="selectedFolderId" placeholder="请选择文件夹" style="width: 100%">
        <el-option
          v-for="folder in folders"
          :key="folder.id"
          :label="folder.folder_name"
          :value="folder.id"
        />
      </el-select>
    </el-card>

    <!-- 文件上传 -->
    <el-card class="upload-card">
      <template #header>
        <span>文件上传</span>
      </template>
      
      <el-upload
        ref="uploadRef"
        :auto-upload="false"
        :multiple="true"
        :limit="10"
        :on-change="handleFileChange"
        :file-list="fileList"
        drag
        class="upload-dragger"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          将文件拖到此处，或<em>点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            支持多文件上传，单个文件不超过100MB
          </div>
        </template>
      </el-upload>

      <div class="upload-actions" v-if="fileList.length > 0">
        <el-button
          type="primary"
          :disabled="!selectedFolderId || uploading"
          :loading="uploading"
          @click="startUpload"
          size="large"
        >
          {{ uploading ? '上传中...' : '开始上传' }}
        </el-button>
        <el-button @click="clearFiles" :disabled="uploading">
          清空文件
        </el-button>
      </div>

      <!-- 上传进度 -->
      <div v-if="uploading" class="progress-area">
        <el-progress
          :percentage="uploadProgress"
          :stroke-width="8"
          text-inside
          status="active"
        />
        <p class="progress-text">{{ progressText }}</p>
      </div>
    </el-card>

    <!-- 文件列表 -->
    <el-card v-if="fileList.length > 0" class="file-list-card">
      <template #header>
        <span>待上传文件 ({{ fileList.length }})</span>
      </template>
      
      <el-table :data="fileList" style="width: 100%">
        <el-table-column prop="name" label="文件名" />
        <el-table-column label="大小" width="120">
          <template #default="{ row }">
            {{ formatFileSize(row.size) }}
          </template>
        </el-table-column>
        <el-table-column label="类型" width="150">
          <template #default="{ row }">
            {{ row.raw.type }}
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80">
          <template #default="{ row, $index }">
            <el-button
              type="danger"
              size="small"
              @click="removeFile($index)"
              :disabled="uploading"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { uploadApi, getFolderApi } from "@/utils/api";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import { UploadFilled } from "@element-plus/icons-vue";

const router = useRouter();

// 响应式数据
const folders = ref([]);
const selectedFolderId = ref(null);
const fileList = ref([]);
const uploading = ref(false);
const uploadProgress = ref(0);
const progressText = ref("");

// 获取文件夹列表
const fetchFolders = async () => {
  try {
    const id = localStorage.getItem("id");
    const response = await getFolderApi({ id });
    if (response.code === 200) {
      folders.value = response.data.data;
      if (folders.value.length > 0) {
        selectedFolderId.value = folders.value[0].id;
      }
    }
  } catch (error) {
    console.error("获取文件夹失败:", error);
    ElMessage.error("获取文件夹失败");
  }
};

// 文件选择处理
const handleFileChange = (uploadFile, uploadFiles) => {
  fileList.value = uploadFiles.map(file => ({
    ...file,
    status: 'ready'
  }));
};

// 开始上传
const startUpload = async () => {
  if (!selectedFolderId.value) {
    ElMessage.warning("请选择文件夹");
    return;
  }

  if (fileList.value.length === 0) {
    ElMessage.warning("请选择文件");
    return;
  }

  uploading.value = true;
  uploadProgress.value = 0;
  
  let successCount = 0;
  let failCount = 0;
  const total = fileList.value.length;

  try {
    for (let i = 0; i < fileList.value.length; i++) {
      const fileItem = fileList.value[i];
      const file = fileItem.raw;
      
      progressText.value = `正在上传: ${file.name} (${i + 1}/${total})`;
      fileItem.status = 'uploading';

      try {
        const formData = new FormData();
        formData.append("file", file);
        formData.append("name", file.name);
        formData.append("size", file.size);
        formData.append("type", file.type);
        formData.append("userId", localStorage.getItem("id"));
        formData.append("folderId", selectedFolderId.value);

        const username = localStorage.getItem("username");
        const response = await uploadApi(username, formData);

        if (response.code === 200) {
          fileItem.status = 'success';
          successCount++;
          ElMessage.success(`${file.name} 上传成功`);
        } else {
          fileItem.status = 'fail';
          failCount++;
          ElMessage.error(`${file.name} 上传失败: ${response.msg}`);
        }
      } catch (error) {
        fileItem.status = 'fail';
        failCount++;
        ElMessage.error(`${file.name} 上传失败: ${error.message}`);
      }

      // 更新进度
      uploadProgress.value = Math.round(((i + 1) / total) * 100);
    }

    // 上传完成
    progressText.value = `上传完成: 成功 ${successCount} 个，失败 ${failCount} 个`;
    
    if (successCount > 0) {
      ElMessage.success(`成功上传 ${successCount} 个文件`);
    }
    
    if (failCount > 0) {
      ElMessage.warning(`${failCount} 个文件上传失败`);
    }

  } finally {
    uploading.value = false;
    
    // 3秒后清空成功的文件
    setTimeout(() => {
      fileList.value = fileList.value.filter(item => item.status !== 'success');
    }, 3000);
  }
};

// 清空文件列表
const clearFiles = () => {
  fileList.value = [];
};

// 删除单个文件
const removeFile = (index) => {
  fileList.value.splice(index, 1);
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 B';
  const k = 1024;
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

// 获取状态类型
const getStatusType = (status) => {
  const types = {
    ready: '',
    uploading: 'warning',
    success: 'success',
    fail: 'danger'
  };
  return types[status] || '';
};

// 获取状态文本
const getStatusText = (status) => {
  const texts = {
    ready: '待上传',
    uploading: '上传中',
    success: '成功',
    fail: '失败'
  };
  return texts[status] || '未知';
};

// 初始化
onMounted(() => {
  fetchFolders();
});
</script>

<style lang="less" scoped>
.upload-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.folder-card,
.upload-card,
.file-list-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-weight: 600;
}

.upload-dragger {
  width: 100%;
}

.upload-actions {
  margin-top: 20px;
  text-align: center;
}

.upload-actions .el-button {
  margin: 0 10px;
}

.progress-area {
  margin-top: 20px;
}

.progress-text {
  text-align: center;
  margin-top: 10px;
  color: #666;
}

.el-icon--upload {
  font-size: 67px;
  color: #c0c4cc;
  margin-bottom: 16px;
}

.el-upload__text {
  color: #606266;
  font-size: 14px;
}

.el-upload__text em {
  color: #409eff;
  font-style: normal;
}

.el-upload__tip {
  color: #999;
  font-size: 12px;
  margin-top: 7px;
}
</style>
